/*
 * JSFConsole - Lightweight JSF Application Monitor
 * Copyright (C) 2009  Grzegorz Bugaj
 * http://www.gregbugaj.com
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
package com.gregbugaj.jsfconsole.agent.tracker;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;

import com.gregbugaj.jsfconsole.Constants;
import com.gregbugaj.jsfconsole.agent.EventType;
import com.gregbugaj.jsfconsole.agent.TraceEvent;
import com.gregbugaj.jsfconsole.agent.TraceEventListener;
import com.gregbugaj.jsfconsole.agent.TraceEventManager;
import com.gregbugaj.jsfconsole.util.Predicate;

/**
 * Track PhaseListeners Lifecycle
 * @author devil
 *
 */
public class PhaseTracker implements Tracker {

	private Predicate<? super TraceEvent>  predicate;

	private TraceEventListener listener;
	private Map<String, PhaseEventInfo> map;
	private Map<String, RequestInfo> requestMap;

	public PhaseTracker(){
		requestMap=Collections.<String, RequestInfo>emptyMap();
	}

	/* (non-Javadoc)
	 * @see com.gregbugaj.jsfdump.agent.tracker.Tracker#startMonitoring()
	 */
	public void startMonitoring(){
		map=new HashMap<String, PhaseEventInfo>();
		requestMap=new HashMap<String, RequestInfo>();
		listener=new TraceEventListener(){

			
			public void trace(TraceEvent traceEvent) {
				//Check if this request is from from our consose , Apply predicate if we have one
				if(predicate!=null && predicate.evaluate(traceEvent)==false){
					return;
				}
				//Arguments passed from the PhaseClassTransformer
				PhaseId phaseId=(PhaseId) traceEvent.getArguments()[1];
				Boolean phaseSkipped=(Boolean)traceEvent.getArguments()[2];

				Integer facesId=traceEvent.getSourceId();

				String key=facesId+":"+phaseId;	
				String fkey=facesId.toString();
				RequestInfo requestInfo=null;

				if(requestMap.get(fkey)==null){
					requestInfo=new RequestInfo(traceEvent.getRequestPath());
					requestMap.put(fkey, requestInfo);
				}else{
					requestInfo=requestMap.get(fkey);
				}
				
				System.out.println("##### traceEvent == "+traceEvent);
				System.out.println("* FacesID = "+facesId);
				System.out.println("* phaseId = "+phaseId);	
				
				PhaseEventInfo info=new PhaseEventInfo();
				info.setPhaseId(phaseId);
				info.setPhaseSkipped(phaseSkipped);
				info.setFacesId(facesId);
				info.setInfo("Phase : "+phaseId);
				info.setRequestPath(traceEvent.getRequestPath());

				if(map.get(key)==null){
					info.setStartTime(traceEvent.getTime());
					map.put(key, info);
				}else{
					info=map.get(key);
					long previousTime=info.getStartTime();
					long elapsedTime=traceEvent.getTime()-previousTime;
					info.setEndTime(traceEvent.getTime());
					info.setElapsedTime(elapsedTime);

					requestInfo.addEventInfo(info);
				}
			}

			
			public String getListenerId() {				
				return PhaseTracker.class.getName()+".TraceEventListener";
			}

		};

		TraceEventManager.registerListener(listener, EventType.PHASE_STARTED, EventType.PHASE_ENDED);
	}

	/* (non-Javadoc)
	 * @see com.gregbugaj.jsfdump.agent.tracker.Tracker#stopMonitoring()
	 */
	public void stopMonitoring(){
		TraceEventManager.removeListener(listener, EventType.PHASE_STARTED, EventType.PHASE_ENDED);
	}

	/* (non-Javadoc)
	 * @see com.gregbugaj.jsfdump.agent.tracker.Tracker#getEvents()
	 */
	public List<RequestInfo> getEvents(int maxCount){
		List<RequestInfo> items = Collections.<RequestInfo>emptyList();  
		Collection<RequestInfo> ri=requestMap.values();
		if(ri!=null){
			items=new ArrayList<RequestInfo>();
			items.addAll(ri);
			Collections.sort(items, RequestInfo.getComparator());
		}
		return items;
	}

	

	public List<RequestInfo> getEvents(int maxCount, String requestPath) {
		//All request need to start with a slash
		if(requestPath==null || requestPath.equals("")){
			requestPath="/";
		}
		List<RequestInfo> items = Collections.<RequestInfo>emptyList();  
		if(predicate==null){
			items =  getEvents(maxCount);
		}else{

			//Copy Items
			Collection<RequestInfo> ri=requestMap.values();
			if(ri!=null){
				items=new ArrayList<RequestInfo>();
				for(RequestInfo info:ri){
					//Apply predicate if we have one
					if(info.getRequestPath().startsWith(requestPath)){
						items.add(info);
					}				
				}
				Collections.sort(items, RequestInfo.getComparator());
			}
		}
		return items;
	}



	public void setFilter(Predicate<? super TraceEvent>  predicate) {
		this.predicate=predicate;	
	}




}
